package com.sakura.flowers.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sakura.flowers.constant.OrderConstant;
import com.sakura.flowers.entity.*;
import com.sakura.flowers.service.*;
import com.sakura.flowers.util.R;
import com.sakura.flowers.vo.FlowerVO;
import com.sakura.flowers.vo.OrderVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * (Orders)表控制层
 *
 * @author Sakura
 * @since 2023-11-26 17:11:07
 */
@Api(value = "/api/orders", tags = {"(Orders)表控制层"})
@RestController
@RequestMapping("/api/order")
@CrossOrigin
public class OrdersController {
    /**
     * 服务对象
     */
    @Resource
    private OrdersService ordersService;
    @Resource
    private FlowerService flowerService;
    @Resource
    private OrderFlowerService orderFlowerService;

    @Resource
    private CardService cardService;
    @Resource
    private CardFlowerService cardFlowerService;

    /**
     * 分页查询
     *
     * @param pageNo   当前页
     * @param pageSize 数据大小
     * @param uid      商家id
     * @return 查询结果
     */
    @ApiOperation(value = "分页查询", notes = "分页查询", httpMethod = "GET")
    @GetMapping("/list/{pageNo}/{pageSize}/{uid}")
    public R queryByPage(@PathVariable Integer pageNo,
                                            @PathVariable Integer pageSize,
                                            @PathVariable(required = false) Long uid) {
        return R.success(this.ordersService.queryByPage(pageNo, pageSize, uid));
    }

    /**
     * 通过主键查询花列表
     *
     * @param id 主键
     * @return 单条数据
     */
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", dataType = "long", name = "id", value = "主键", required = true)
    })
    @ApiOperation(value = "通过主键查询花列表", notes = "通过主键查询花列表", httpMethod = "GET")
    @GetMapping("{id}")
    public R queryById(@PathVariable("id") Long id) {
        return R.success(ordersService.getFlowerList(id));
    }

    /**
     * 删除数据
     *
     * @param id 主键
     * @return 删除是否成功
     */
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", dataType = "long", name = "id", value = "主键", required = true)
    })
    @ApiOperation(value = "删除数据", notes = "删除数据", httpMethod = "DELETE")
    @DeleteMapping("/{id}")
    public R deleteById(@PathVariable Long id) {
        boolean result = this.ordersService.removeById(id);
        if (!result) {
            return R.error("删除失败");
        }
        return R.success("删除成功");
    }

    @PutMapping("/cancel/{oid}")
    public R getById(@PathVariable("oid") long oid) {
        Orders order = ordersService.getById(oid);
        order.setCancel(OrderConstant.CANCELED);
        boolean update = ordersService.updateById(order);
        if (!update) {
            return R.error("取消失败,请重新尝试");
        }
        return R.success("取消成功");
    }


    //通过用户id获取订单
    @GetMapping("/{userId}/{cancel}")
    public R queryByUserId(@PathVariable("userId") Long userId,@PathVariable("cancel") int cancel) {
        LambdaQueryWrapper<Orders> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(Orders::getUserId, userId);
        lambdaQueryWrapper.orderByDesc(Orders::getCreateTime);
        if (cancel==0){
            lambdaQueryWrapper.in(Orders::getCancel, Arrays.asList(0,3));
        }else {
            lambdaQueryWrapper.eq(cancel!=-1,Orders::getCancel,cancel);
        }
        List<Orders> list = ordersService.list(lambdaQueryWrapper);
//        Page page1 = ordersService.page(page, lambdaQueryWrapper);

        List<OrderVO> orderVOS = new ArrayList<>();
        for (Orders orders : list) {
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(orders, orderVO);
            orderVO.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(orders.getCreateTime()));
            LambdaQueryWrapper<OrderFlower> orderCardWrapper = new LambdaQueryWrapper();
            orderCardWrapper.eq(OrderFlower::getOrderId, orders.getId());
            List<OrderFlower> list1 = orderFlowerService.list(orderCardWrapper);
            List<FlowerVO> medicineVOS = new ArrayList<>();
            for (OrderFlower orderCard : list1) {
                LambdaQueryWrapper<Flower> medicineLambdaQueryWrapper = new LambdaQueryWrapper<>();
                medicineLambdaQueryWrapper.eq(Flower::getId, orderCard.getFlowerId());
                Flower medicine = flowerService.getOne(medicineLambdaQueryWrapper);
                FlowerVO medicineVO = new FlowerVO();
                medicineVO.setId(medicine.getId());
                medicineVO.setCount(orderCard.getNum());
                medicineVO.setImage(medicine.getImage());
                medicineVO.setName(medicine.getName());
                medicineVO.setPrice(medicine.getPrice());
                medicineVO.setAttrsText(medicine.getContent());
                medicineVOS.add(medicineVO);
            }
            orderVO.setFlowerVOS(medicineVOS);
            orderVOS.add(orderVO);
        }
        return R.success(orderVOS);
    }



    @PostMapping("/cancel")
    public R cancel(@RequestBody Orders orders) {
        orders.setCancel(1);
        this.ordersService.updateById(orders);
        return R.success("成功");
    }

    @PutMapping("/send/{oid}")
    public R send(@PathVariable Long oid) {
        Orders orders = ordersService.getById(oid);
        orders.setCancel(OrderConstant.SEND);
        boolean update = this.ordersService.updateById(orders);
        if (!update) {
            return R.error("失败,请重新尝试");
        }
        return R.success("成功");
    }

    @PutMapping("/finished/{oid}")
    public R finished(@PathVariable Long oid) {
        Orders orders = ordersService.getById(oid);
        orders.setCancel(OrderConstant.FINISHED);
        boolean update = this.ordersService.updateById(orders);
        if (!update) {
            return R.error("失败,请重新尝试");
        }
        return R.success("成功");
    }

    @GetMapping("/createOrder")
    public R createOrder(@RequestParam long id) {
        System.out.println(id);
        LambdaQueryWrapper<Card> lambdaQueryWrapper=new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(Card::getUserId,id);
        Card card = cardService.getOne(lambdaQueryWrapper);
        List<CardFlower> cardMedicines=new ArrayList<>();
        if (card!=null){
            LambdaQueryWrapper<CardFlower> cardMedicineQueryWrapper=new LambdaQueryWrapper();
            cardMedicineQueryWrapper.eq(CardFlower::getCardId,card.getId());
            cardMedicineQueryWrapper.eq(CardFlower::getSelected,1);
            cardMedicines = cardFlowerService.list(cardMedicineQueryWrapper);
        }
        double price=0.0;
        boolean flag=false;
        long uuid= getUUID();
        Map<Long,Long> floristMap=new HashMap<>();
        for (CardFlower cardMedicine : cardMedicines) {
            Flower medicine = flowerService.getById(cardMedicine.getFlowerId());

            price+=medicine.getPrice()*cardMedicine.getSum();
//            if (medicine.getIsPrescription()==1){
//                flag=true;
//            }
            OrderFlower orderCard=new OrderFlower();
            orderCard.setOrderId(uuid);
            orderCard.setFlowerId(medicine.getId());
            orderCard.setNum(cardMedicine.getSum());
            orderFlowerService.save(orderCard);
            LambdaQueryWrapper<CardFlower> cardMedicineLambdaQueryWrapper=new LambdaQueryWrapper<>();
            cardMedicineLambdaQueryWrapper.eq(CardFlower::getFlowerId,medicine.getId());
            CardFlower one = cardFlowerService.getOne(cardMedicineLambdaQueryWrapper);
            cardFlowerService.deleteById(one.getId());

            if (!floristMap.containsKey(medicine.getFlorist())){
                floristMap.put(medicine.getFlorist(),uuid);
                Orders orders = new Orders();
                orders.setId(uuid);
                orders.setUserId(id);
                orders.setPrice(price);
                orders.setCreateTime(new Date());
//        orders.setStatus(flag?"0":"2");
                orders.setCancel(0);
                orders.setShopId(medicine.getFlorist());
                ordersService.save(orders);
                uuid= getUUID();
            }
        }

//        if (flag){
//            return R.success("订单包含处方药，请前往我的订单上传处方审核");
//        }else {
            return R.success("下单成功");
//        }
    }

    public static long getUUID() {
        String id =null;
        UUID uuid = UUID.randomUUID();
        id = uuid.toString();

        //去掉随机ID的短横线
        id = id.replace("-", "");

        //将随机ID换成数字
        int num = id.hashCode();
        //去绝对值
        num = num < 0 ? -num : num;

        id = String.valueOf(num);

        return Long.parseLong(id);
    }

}
